<template>
  <q-page class="q-pa-md">
    <!-- 拖拽上传区域 -->
    <div
      v-if="showDropZone"
      class="drop-zone"
      @drop="handleDrop"
      @dragover="handleDragOver"
      @dragleave="handleDragLeave"
      @dragenter="handleDragEnter"
    >
      <div class="drop-zone-content">
        <q-icon name="cloud_upload" size="64px" color="primary" />
        <div class="text-h6 text-primary q-mt-md">拖拽文件到此处上传</div>
        <div class="text-caption text-grey-6 q-mt-sm">支持多文件拖拽</div>
      </div>
    </div>

    <!-- 顶部工具栏 -->
    <div class="row items-center justify-between q-mb-md">
      <!-- 面包屑导航 -->
      <q-breadcrumbs>
        <q-breadcrumbs-el
          v-for="(item, index) in breadcrumbs"
          :key="index"
          :label="item.label"
          :icon="item.icon"
          @click="navigateToBreadcrumb(index)"
        />
      </q-breadcrumbs>

      <!-- 右侧工具栏 -->
      <div class="row items-center q-gutter-sm">
        <!-- 选择模式下的工具栏 -->
        <template v-if="selectedItems.length > 0">
          <!-- 显示选中项目数量 -->
          <div class="text-caption text-grey-6 q-mr-sm">
            已选择 {{ selectedItems.length }} 项
          </div>
          <!-- 单个项目选择时的工具栏 -->
          <template v-if="selectedItems.length === 1">
            <template v-if="selectedItems[0].file_type === 'directory'">
              <q-btn flat round icon="cloud_upload" @click="handleUpload" />
              <q-btn flat round icon="edit" @click="handleRename" />
              <q-btn flat round icon="delete" @click="handleDelete" />
              <q-btn flat round icon="image" @click="handleImageHost" />
            </template>
            <template v-else>
              <q-btn flat round icon="download" @click="handleDownload" />
              <q-btn flat round icon="edit" @click="handleRename" />
              <q-btn flat round icon="delete" @click="handleDelete" />
              <q-btn flat round icon="link" @click="handleGetLink" />
            </template>
          </template>
          <!-- 多个项目选择时的工具栏 -->
          <template v-else>
            <!-- 如果有选中的文件，显示下载按钮 -->
            <q-btn
              v-if="selectedFiles.length > 0"
              flat
              round
              icon="download"
              @click="handleDownload"
            >
              <q-tooltip>批量下载</q-tooltip>
            </q-btn>
            <!-- 删除按钮始终显示 -->
            <q-btn flat round icon="delete" @click="handleDelete">
              <q-tooltip>批量删除</q-tooltip>
            </q-btn>
          </template>
          <q-btn flat round icon="close" @click="clearSelection" />
        </template>
        <!-- 正常模式下的工具栏 -->
        <template v-else>
          <q-btn
            flat
            round
            :icon="refreshing ? 'sync' : 'refresh'"
            :loading="refreshing"
            @click="refreshDirectory"
          >
            <q-tooltip>刷新目录 (F5)</q-tooltip>
          </q-btn>
          <q-btn
            flat
            round
            icon="create_new_folder"
            @click="handleCreateFolder"
          >
            <q-tooltip>新建文件夹</q-tooltip>
          </q-btn>
          <q-btn flat round icon="cloud_upload" @click="handleUpload">
            <q-tooltip>上传文件</q-tooltip>
          </q-btn>
        </template>
      </div>
    </div>

    <!-- 文件夹列表 -->
    <div v-if="folders.length > 0" class="q-mb-lg">
      <h6 class="q-mb-md">文件夹</h6>
      <div class="item-list">
        <div class="item-header">
          <div class="header-checkbox">
            <q-checkbox
              v-model="selectAllFolders"
              @update:model-value="toggleSelectAllFolders"
              :indeterminate="isPartiallySelectedFolders"
            />
          </div>
          <div class="header-name">名称</div>
          <div class="header-type">类型</div>
          <div class="header-time">修改时间</div>
          <div class="header-size">大小</div>
        </div>
        <div
          v-for="folder in folders"
          :key="folder.full_path"
          class="item-row"
          :class="{ 'item-selected': isItemSelected(folder) }"
          @click="handleItemClick(folder, $event)"
          @contextmenu="handleContextMenu($event, folder)"
        >
          <div class="item-checkbox">
            <q-checkbox
              v-model="selectedItems"
              :val="folder"
              @update:model-value="handleItemSelect"
            />
          </div>
          <div class="item-name-cell">
            <q-icon
              name="folder"
              size="20px"
              color="primary"
              class="item-icon"
            />
            <span class="item-name">{{ folder.filename }}</span>
          </div>
          <div class="item-type">文件夹</div>
          <div class="item-time">{{ formatTime(folder.last_modified) }}</div>
          <div class="item-size">-</div>
        </div>
      </div>
    </div>

    <!-- 文件列表 -->
    <div v-if="files.length > 0">
      <h6 class="q-mb-md">文件</h6>
      <div class="item-list">
        <div class="item-header">
          <div class="header-checkbox">
            <q-checkbox
              v-model="selectAllFiles"
              @update:model-value="toggleSelectAllFiles"
              :indeterminate="isPartiallySelectedFiles"
            />
          </div>
          <div class="header-name">名称</div>
          <div class="header-type">类型</div>
          <div class="header-time">修改时间</div>
          <div class="header-size">大小</div>
        </div>
        <div
          v-for="file in files"
          :key="file.full_path"
          class="item-row"
          :class="{ 'item-selected': isItemSelected(file) }"
          @click="handleItemClick(file, $event)"
          @contextmenu="handleContextMenu($event, file)"
        >
          <div class="item-checkbox">
            <q-checkbox
              v-model="selectedItems"
              :val="file"
              @update:model-value="handleItemSelect"
            />
          </div>
          <div class="item-name-cell">
            <q-icon
              :name="getFileIcon(file)"
              size="20px"
              :color="getFileColor(file)"
              class="item-icon"
            />
            <span class="item-name">{{ file.filename }}</span>
          </div>
          <div class="item-type">{{ getFileType(file) }}</div>
          <div class="item-time">{{ formatTime(file.last_modified) }}</div>
          <div class="item-size">{{ formatFileSize(file.size) }}</div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div
      v-if="!loading && folders.length === 0 && files.length === 0"
      class="text-center q-pa-xl"
      @contextmenu="handleContextMenu($event, null)"
    >
      <q-icon name="folder_open" size="64px" color="grey-4" />
      <div class="text-h6 text-grey-6 q-mt-md">当前目录为空</div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="text-center q-pa-xl">
      <q-spinner-dots size="50px" color="primary" />
      <div class="text-h6 text-grey-6 q-mt-md">加载中...</div>
    </div>

    <!-- 处理数据时的inner loading -->
    <q-inner-loading :showing="processingData">
      <q-spinner-ios size="20px" color="primary" />
    </q-inner-loading>

    <!-- 图床设置对话框 -->
    <q-dialog v-model="showImageHostDialogVisible" persistent>
      <q-card style="min-width: 500px; max-width: 600px">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">图床设置</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="q-pt-none">
          <div v-if="imageHostTarget" class="text-subtitle2 q-mb-md">
            文件夹：{{ imageHostTarget.filename }}
          </div>

          <!-- 未启用状态 -->
          <div v-if="!imageHostConfig?.enabled" class="text-center q-pa-lg">
            <q-icon name="image" size="64px" color="grey-4" />
            <div class="text-h6 text-grey-6 q-mt-md">图床功能未启用</div>
            <div class="text-caption text-grey-5 q-mt-sm">
              启用后可以将此文件夹作为图床使用
            </div>
            <q-btn
              color="primary"
              label="启用图床功能"
              @click="enableImageHost"
              class="q-mt-md"
            />
          </div>

          <!-- 已启用状态 -->
          <div v-else class="q-gutter-y-md">
            <div class="row items-center justify-between">
              <div class="text-subtitle1">图床配置信息</div>
              <q-btn
                flat
                round
                icon="help"
                @click="showImageHostHelp"
                color="primary"
              >
                <q-tooltip>使用帮助</q-tooltip>
              </q-btn>
            </div>

            <q-list bordered separator>
              <q-item>
                <q-item-section>
                  <q-item-label caption>上传路径</q-item-label>
                  <q-item-label>{{ imageHostConfig.upload_path }}</q-item-label>
                </q-item-section>
                <q-item-section side>
                  <q-btn
                    flat
                    round
                    icon="content_copy"
                    @click="copyToClipboard(imageHostConfig.upload_path)"
                    size="sm"
                  >
                    <q-tooltip>复制路径</q-tooltip>
                  </q-btn>
                </q-item-section>
              </q-item>

              <q-item>
                <q-item-section>
                  <q-item-label caption>访问Token</q-item-label>
                  <q-item-label class="text-monospace">{{
                    imageHostConfig.token
                  }}</q-item-label>
                </q-item-section>
                <q-item-section side>
                  <q-btn
                    flat
                    round
                    icon="content_copy"
                    @click="copyToClipboard(imageHostConfig.token)"
                    size="sm"
                  >
                    <q-tooltip>复制Token</q-tooltip>
                  </q-btn>
                </q-item-section>
              </q-item>

              <q-item>
                <q-item-section>
                  <q-item-label caption>创建时间</q-item-label>
                  <q-item-label>{{
                    formatTime(imageHostConfig.create_time)
                  }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-list>

            <div class="row q-gutter-sm q-mt-md">
              <q-btn
                color="warning"
                label="刷新Token"
                icon="refresh"
                @click="refreshToken"
              />
              <q-btn
                color="negative"
                label="取消图床功能"
                icon="delete"
                @click="disableImageHost"
              />
            </div>
          </div>
        </q-card-section>
      </q-card>
    </q-dialog>

    <!-- 上下文菜单 -->
    <div
      v-if="showContextMenu"
      class="context-menu"
      :style="{
        left: contextMenuPosition.x + 'px',
        top: contextMenuPosition.y + 'px',
      }"
      @click.stop
    >
      <q-list
        style="
          min-width: 200px;
          background: white;
          border: 1px solid #ddd;
          border-radius: 4px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        "
      >
        <!-- 空白处右键菜单 -->
        <template v-if="contextMenuData === null">
          <q-item clickable @click="handleContextMenuClick('refresh')">
            <q-item-section avatar>
              <q-icon name="refresh" />
            </q-item-section>
            <q-item-section>刷新</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('createFolder')">
            <q-item-section avatar>
              <q-icon name="create_new_folder" />
            </q-item-section>
            <q-item-section>新建文件夹</q-item-section>
          </q-item>
        </template>

        <!-- 文件夹右键菜单 -->
        <template
          v-else-if="
            contextMenuData && contextMenuData.file_type === 'directory'
          "
        >
          <q-item clickable @click="handleContextMenuClick('upload')">
            <q-item-section avatar>
              <q-icon name="cloud_upload" />
            </q-item-section>
            <q-item-section>上传文件</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('rename')">
            <q-item-section avatar>
              <q-icon name="edit" />
            </q-item-section>
            <q-item-section>重命名</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('delete')">
            <q-item-section avatar>
              <q-icon name="delete" />
            </q-item-section>
            <q-item-section>删除</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('imageHost')">
            <q-item-section avatar>
              <q-icon name="image" />
            </q-item-section>
            <q-item-section>图床设置</q-item-section>
          </q-item>
        </template>

        <!-- 文件右键菜单 -->
        <template
          v-else-if="
            contextMenuData && contextMenuData.file_type !== 'directory'
          "
        >
          <q-item clickable @click="handleContextMenuClick('download')">
            <q-item-section avatar>
              <q-icon name="download" />
            </q-item-section>
            <q-item-section>下载</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('rename')">
            <q-item-section avatar>
              <q-icon name="edit" />
            </q-item-section>
            <q-item-section>重命名</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('delete')">
            <q-item-section avatar>
              <q-icon name="delete" />
            </q-item-section>
            <q-item-section>删除</q-item-section>
          </q-item>
          <q-item clickable @click="handleContextMenuClick('getLink')">
            <q-item-section avatar>
              <q-icon name="link" />
            </q-item-section>
            <q-item-section>获取临时直链</q-item-section>
          </q-item>
        </template>
      </q-list>
    </div>
  </q-page>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { useQuasar } from "quasar";
import taskQueue, { TaskType } from "src/js/taskQueue";

defineOptions({
  name: "IndexPage",
});

// 定义props和emits
const props = defineProps({
  directoryData: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update-current-path", "offline-download"]);

const $q = useQuasar();

// 响应式数据
const currentPath = ref("/");
const loading = ref(false);
const refreshing = ref(false); // 刷新状态
const processingData = ref(false); // 处理数据状态
const viewMode = ref("grid"); // grid 或 list
const allItems = ref([]); // 所有项目（包含嵌套结构）
const currentDirectoryItems = ref([]); // 当前目录的项目

// 拖拽上传相关
const showDropZone = ref(false);
const dragCounter = ref(0);

// 选择相关状态
const selectedItems = ref([]); // 选中的项目
const showContextMenu = ref(false); // 是否显示上下文菜单
const contextMenuPosition = ref({ x: 0, y: 0 }); // 上下文菜单位置
const contextMenuTarget = ref(null); // 上下文菜单目标DOM元素
const contextMenuData = ref(null); // 上下文菜单数据

// 防抖刷新相关
const refreshTimeout = ref(null);
const pendingRefresh = ref(false);
const completedTasks = ref([]); // 已完成的任务列表

// 批量上传相关
const batchUploadCount = ref(0); // 批量上传的文件数量
const completedUploadCount = ref(0); // 已完成的上传数量
const batchUploadTimeout = ref(null); // 批量上传汇总通知的定时器

// 计算属性
const breadcrumbs = computed(() => {
  const paths = currentPath.value.split("/").filter((p) => p);
  const result = [{ label: "我的文件", icon: "folder", path: "/" }];

  let currentFullPath = "";
  paths.forEach((path, index) => {
    currentFullPath += "/" + path;
    result.push({
      label: path,
      icon: index === paths.length - 1 ? "expand_more" : null,
      path: currentFullPath,
    });
  });

  return result;
});

// 选择相关计算属性
const selectedFolders = computed(() => {
  return selectedItems.value.filter((item) => item.file_type === "directory");
});

const selectedFiles = computed(() => {
  return selectedItems.value.filter((item) => item.file_type !== "directory");
});

const hasSelectedFolders = computed(() => {
  return selectedFolders.value.length > 0;
});

const selectAllFolders = computed({
  get() {
    return (
      folders.value.length > 0 &&
      selectedFolders.value.length === folders.value.length
    );
  },
  set(value) {
    if (value) {
      // 选中所有文件夹
      const newSelected = [...selectedItems.value];
      folders.value.forEach((folder) => {
        if (!newSelected.find((item) => item.full_path === folder.full_path)) {
          newSelected.push(folder);
        }
      });
      selectedItems.value = newSelected;
    } else {
      // 取消选中所有文件夹
      selectedItems.value = selectedItems.value.filter(
        (item) => item.file_type !== "directory"
      );
    }
  },
});

const selectAllFiles = computed({
  get() {
    return (
      files.value.length > 0 &&
      selectedFiles.value.length === files.value.length
    );
  },
  set(value) {
    if (value) {
      // 选中所有文件
      const newSelected = [...selectedItems.value];
      files.value.forEach((file) => {
        if (!newSelected.find((item) => item.full_path === file.full_path)) {
          newSelected.push(file);
        }
      });
      selectedItems.value = newSelected;
    } else {
      // 取消选中所有文件
      selectedItems.value = selectedItems.value.filter(
        (item) => item.file_type === "directory"
      );
    }
  },
});

const isPartiallySelectedFolders = computed(() => {
  return (
    selectedFolders.value.length > 0 &&
    selectedFolders.value.length < folders.value.length
  );
});

const isPartiallySelectedFiles = computed(() => {
  return (
    selectedFiles.value.length > 0 &&
    selectedFiles.value.length < files.value.length
  );
});

// 根据当前路径过滤显示的项目
const updateCurrentDirectoryItems = () => {
  if (!allItems.value || allItems.value.length === 0) {
    currentDirectoryItems.value = [];
    return;
  }

  // 如果当前在根目录
  if (currentPath.value === "/") {
    // 只显示根目录的项目（不包含子目录中的项目）
    currentDirectoryItems.value = allItems.value.filter((item) => {
      const pathParts = item.full_path.split("/");
      // 移除cloud/user-id部分后，如果只剩下文件名，说明是根目录项目
      // 注意：split("/")会在末尾的"/"后产生空字符串
      return (
        pathParts.length === 3 ||
        (pathParts.length === 4 && pathParts[3] === "")
      );
    });
  } else {
    // 显示指定目录下的项目
    const targetPath = currentPath.value;

    // 递归查找目标目录
    const findTargetFolder = (items, targetPath) => {
      for (const item of items) {
        if (item.file_type === "directory") {
          const folderPath = getItemPath(item.full_path);
          if (folderPath === targetPath) {
            return item;
          }
          // 如果这个目录有子项目，递归查找
          if (item.items && item.items.length > 0) {
            const found = findTargetFolder(item.items, targetPath);
            if (found) {
              return found;
            }
          }
        }
      }
      return null;
    };

    // 从allItems中递归查找目标目录
    const targetFolder = findTargetFolder(allItems.value, targetPath);

    console.log("找到的目标文件夹:", targetFolder);

    if (targetFolder && targetFolder.items) {
      // 如果找到了目录项且有items，直接使用
      currentDirectoryItems.value = targetFolder.items;
      console.log("使用文件夹的items:", targetFolder.items);
    } else {
      // 如果没找到，尝试按路径过滤（作为备用方案）
      currentDirectoryItems.value = allItems.value.filter((item) => {
        const itemDir = getItemDirectory(item.full_path);
        return itemDir === targetPath;
      });
      console.log("使用过滤逻辑的结果:", currentDirectoryItems.value);
    }
  }

  console.log("当前路径:", currentPath.value);
  console.log("当前目录项目:", currentDirectoryItems.value);
};

const folders = computed(() => {
  const data = currentDirectoryItems.value;
  if (!data) return [];
  const folderItems =
    data.filter((item) => item.file_type === "directory") || [];
  console.log("文件夹列表:", folderItems);
  return folderItems;
});

const files = computed(() => {
  const data = currentDirectoryItems.value;
  if (!data) return [];
  const fileItems = data.filter((item) => item.file_type !== "directory") || [];
  console.log("文件列表:", fileItems);
  return fileItems;
});

// 方法

// 选择相关方法
const isItemSelected = (item) => {
  return selectedItems.value.some(
    (selected) => selected.full_path === item.full_path
  );
};

const handleItemClick = (item, event) => {
  // 如果点击的是复选框，不处理
  if (event.target.closest(".q-checkbox")) {
    return;
  }

  // 如果当前有选中项目，则点击项目时切换选择状态
  if (selectedItems.value.length > 0) {
    const isSelected = isItemSelected(item);
    if (isSelected) {
      selectedItems.value = selectedItems.value.filter(
        (selected) => selected.full_path !== item.full_path
      );
    } else {
      selectedItems.value.push(item);
    }
  } else {
    // 如果没有选中项目，则正常打开文件或文件夹
    if (item.file_type === "directory") {
      openFolder(item);
    } else {
      openFile(item);
    }
  }
};

const handleItemSelect = () => {
  // 这个方法会在复选框状态改变时被调用
  // 由于我们使用了v-model，Vue会自动处理selectedItems的更新
};

const clearSelection = () => {
  selectedItems.value = [];
};

const toggleSelectAllFolders = (value) => {
  selectAllFolders.value = value;
};

const toggleSelectAllFiles = (value) => {
  selectAllFiles.value = value;
};

// 上下文菜单相关方法
const handleContextMenu = (event, target) => {
  event.preventDefault();
  event.stopPropagation();

  console.log("上下文菜单触发:", { target, event: event.type });

  // 设置菜单数据
  contextMenuData.value = target;

  // 计算菜单位置，确保菜单在视窗内
  const menuWidth = 200; // 菜单宽度
  const menuHeight = 250; // 预估菜单高度
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;

  let x = event.clientX;
  let y = event.clientY;

  // 确保菜单不会超出右边界
  if (x + menuWidth > windowWidth) {
    x = windowWidth - menuWidth - 10;
  }

  // 确保菜单不会超出下边界
  if (y + menuHeight > windowHeight) {
    y = windowHeight - menuHeight - 10;
  }

  // 确保菜单不会超出左边界
  if (x < 10) {
    x = 10;
  }

  // 确保菜单不会超出上边界
  if (y < 10) {
    y = 10;
  }

  contextMenuPosition.value = { x, y };

  // 显示菜单
  showContextMenu.value = true;

  console.log("菜单状态:", {
    showContextMenu: showContextMenu.value,
    contextMenuPosition: contextMenuPosition.value,
    contextMenuData: contextMenuData.value,
  });
};

// 上下文菜单点击处理
const handleContextMenuClick = (action) => {
  // 关闭菜单
  showContextMenu.value = false;

  // 根据动作执行相应的处理
  switch (action) {
    case "refresh":
      refreshDirectory();
      break;
    case "createFolder":
      handleCreateFolder();
      break;
    case "upload":
      handleUpload();
      break;
    case "rename":
      handleRename();
      break;
    case "delete":
      handleDelete();
      break;
    case "download":
      handleDownload();
      break;
    case "getLink":
      handleGetLink();
      break;
    case "imageHost":
      handleImageHost();
      break;
  }
};

// 操作相关方法
const handleUpload = () => {
  // 创建隐藏的文件输入元素
  const fileInput = document.createElement("input");
  fileInput.type = "file";
  fileInput.multiple = true; // 支持多文件选择
  fileInput.style.display = "none";

  // 添加文件选择事件监听器
  fileInput.addEventListener("change", async (event) => {
    const files = Array.from(event.target.files);

    if (files.length === 0) {
      document.body.removeChild(fileInput);
      return;
    }

    // 文件验证
    const maxFileSize = 200 * 1024 * 1024; // 200MB
    const validFiles = [];
    const invalidFiles = [];

    for (const file of files) {
      // 检查文件大小
      if (file.size > maxFileSize) {
        invalidFiles.push(`${file.name} (文件过大，超过100MB)`);
        continue;
      }

      // 检查文件名长度
      if (file.name.length > 255) {
        invalidFiles.push(`${file.name} (文件名过长，超过255字符)`);
        continue;
      }

      // 检查文件名是否包含非法字符
      const invalidChars = /[<>:"/\\|?*]/;
      if (invalidChars.test(file.name)) {
        invalidFiles.push(`${file.name} (文件名包含非法字符)`);
        continue;
      }

      validFiles.push(file);
    }

    // 显示无效文件警告
    if (invalidFiles.length > 0) {
      $q.notify({
        type: "warning",
        message: `以下文件无法上传：\n${invalidFiles.join("\n")}`,
        position: "top",
        timeout: 5000,
        html: true,
      });
    }

    // 如果没有有效文件，直接返回
    if (validFiles.length === 0) {
      document.body.removeChild(fileInput);
      return;
    }

    try {
      // 记录批量上传数量
      if (validFiles.length > 1) {
        batchUploadCount.value = validFiles.length;
        completedUploadCount.value = 0;
      }

      // 为每个有效文件创建上传任务
      for (let i = 0; i < validFiles.length; i++) {
        const file = validFiles[i];

        // 添加到任务队列
        taskQueue.addTask(TaskType.UPLOAD, {
          file: file,
          targetPath: currentPath.value,
        });
      }

      // 成功通知
      if (validFiles.length === 1) {
        $q.notify({
          type: "positive",
          message: `已添加上传任务到队列`,
          position: "top",
          timeout: 2000,
        });
      } else {
        $q.notify({
          type: "positive",
          message: `已添加 ${validFiles.length} 个上传任务到队列`,
          position: "top",
          timeout: 2000,
        });
      }
    } catch (error) {
      console.error("添加上传任务失败:", error);
      $q.notify({
        type: "negative",
        message: "添加上传任务失败: " + (error.message || "未知错误"),
        position: "top",
        timeout: 3000,
      });
    }

    // 清理文件输入元素
    document.body.removeChild(fileInput);
  });

  // 添加错误处理
  fileInput.addEventListener("error", (error) => {
    console.error("文件选择错误:", error);
    $q.notify({
      type: "negative",
      message: "文件选择失败",
      position: "top",
      timeout: 3000,
    });
    document.body.removeChild(fileInput);
  });

  // 将文件输入元素添加到页面并触发点击
  document.body.appendChild(fileInput);
  fileInput.click();
};

const handleCreateFolder = () => {
  // 弹出输入对话框
  $q.dialog({
    title: "新建文件夹",
    message: "请输入文件夹名称:",
    prompt: {
      model: "",
      type: "text",
      isValid: (val) => {
        if (!val || val.trim().length === 0) {
          return "文件夹名称不能为空";
        }
        if (val.length > 255) {
          return "文件夹名称不能超过255个字符";
        }
        // 检查是否包含非法字符
        const invalidChars = /[<>:"/\\|?*]/;
        if (invalidChars.test(val)) {
          return '文件夹名称不能包含以下字符: < > : " / \\ | ? *';
        }
        // 检查是否已存在同名文件夹
        const existingFolder = folders.value.find(
          (folder) => folder.filename === val.trim()
        );
        if (existingFolder) {
          return "已存在同名文件夹";
        }
        return true;
      },
    },
    cancel: true,
    persistent: true,
  }).onOk(async (folderName) => {
    const trimmedName = folderName.trim();

    try {
      // 添加到任务队列
      taskQueue.addTask(TaskType.CREATE_FOLDER, {
        folderName: trimmedName,
        targetPath: currentPath.value,
      });

      // 成功通知
      $q.notify({
        type: "positive",
        message: `已添加创建文件夹任务到队列`,
        position: "top",
        timeout: 3000,
      });
    } catch (error) {
      console.error("添加创建文件夹任务失败:", error);
      $q.notify({
        type: "negative",
        message: "添加创建文件夹任务失败: " + (error.message || "未知错误"),
        position: "top",
        timeout: 3000,
      });
    }
  });
};

const handleRename = () => {
  const target =
    contextMenuData.value ||
    (selectedItems.value.length === 1 ? selectedItems.value[0] : null);

  if (!target) {
    $q.notify({
      type: "warning",
      message: "请选择要重命名的项目",
      position: "top",
    });
    return;
  }

  // 弹出输入对话框
  $q.dialog({
    title: "重命名",
    message: "请输入新的名称:",
    prompt: {
      model: target.filename,
      type: "text",
      isValid: (val) => val.length > 0 && val.length <= 255,
    },
    cancel: true,
    persistent: true,
  }).onOk(async (newName) => {
    if (newName === target.filename) {
      $q.notify({
        type: "info",
        message: "名称未发生变化",
        position: "top",
      });
      return;
    }

    try {
      // 添加到任务队列
      taskQueue.addTask(TaskType.RENAME, {
        oldPath: target.full_path,
        newName: newName,
      });

      // 成功通知
      $q.notify({
        type: "positive",
        message: `已添加重命名任务到队列`,
        position: "top",
        timeout: 3000,
      });

      // 清除选择
      clearSelection();
    } catch (error) {
      console.error("添加重命名任务失败:", error);
      $q.notify({
        type: "negative",
        message: "添加重命名任务失败: " + (error.message || "未知错误"),
        position: "top",
        timeout: 3000,
      });
    }
  });
};

const handleDelete = () => {
  const itemsToDelete = contextMenuData.value
    ? [contextMenuData.value]
    : selectedItems.value;

  if (itemsToDelete.length === 0) {
    $q.notify({
      type: "warning",
      message: "请选择要删除的项目",
      position: "top",
    });
    return;
  }

  // 构建确认消息
  let message = "确定要删除以下项目吗？\n";
  if (itemsToDelete.length <= 5) {
    // 如果项目数量少于等于5个，显示所有名称
    const names = itemsToDelete.map((item) => item.filename).join("\n");
    message += names;
  } else {
    // 如果项目数量大于5个，只显示前3个，然后显示剩余数量
    const firstNames = itemsToDelete
      .slice(0, 3)
      .map((item) => item.filename)
      .join("\n");
    const remainingCount = itemsToDelete.length - 3;
    message += `${firstNames}\n... 还有 ${remainingCount} 个项目`;
  }

  // 弹出确认对话框
  $q.dialog({
    title: "确认删除",
    message: message,
    cancel: true,
    persistent: true,
    ok: {
      label: "删除",
      color: "negative",
    },
  }).onOk(async () => {
    try {
      // 为每个项目创建删除任务
      for (let i = 0; i < itemsToDelete.length; i++) {
        const item = itemsToDelete[i];

        // 添加到任务队列
        taskQueue.addTask(TaskType.DELETE, {
          filePath: item.full_path,
        });
      }

      // 成功通知
      $q.notify({
        type: "positive",
        message: `已添加 ${itemsToDelete.length} 个删除任务到队列`,
        position: "top",
        timeout: 3000,
      });

      // 清除选择
      clearSelection();
    } catch (error) {
      console.error("添加删除任务失败:", error);
      $q.notify({
        type: "negative",
        message: "添加删除任务失败: " + (error.message || "未知错误"),
        position: "top",
        timeout: 3000,
      });
    }
  });
};

const handleDownload = async () => {
  const itemsToDownload = contextMenuData.value
    ? [contextMenuData.value]
    : selectedFiles.value;

  if (itemsToDownload.length === 0) {
    $q.notify({
      type: "warning",
      message: "请选择要下载的文件",
      position: "top",
    });
    return;
  }

  try {
    // 为每个文件直接打开下载链接
    for (let i = 0; i < itemsToDownload.length; i++) {
      const file = itemsToDownload[i];

      // 显示加载通知
      const loadingNotify = $q.notify({
        type: "info",
        message: `正在获取 ${file.filename} 的下载链接...`,
        position: "top",
        timeout: 0,
      });

      try {
        // 导入API
        const { getDownloadInfo } = await import("src/js/cloudApi");

        // 获取下载信息
        const downloadInfo = await getDownloadInfo(file.full_path);

        // 关闭加载通知
        loadingNotify();

        // 在新窗口打开下载链接
        window.open(downloadInfo.download_url, "_blank");

        // 短暂延迟，避免浏览器阻止多个弹窗
        await new Promise((resolve) => setTimeout(resolve, 500));
      } catch (error) {
        loadingNotify();
        console.error(`获取 ${file.filename} 下载链接失败:`, error);
        $q.notify({
          type: "negative",
          message: `获取 ${file.filename} 下载链接失败: ${
            error.message || "未知错误"
          }`,
          position: "top",
          timeout: 3000,
        });
      }
    }

    // 成功通知
    $q.notify({
      type: "positive",
      message: `已打开 ${itemsToDownload.length} 个文件的下载链接`,
      position: "top",
      timeout: 3000,
    });

    // 清除选择
    clearSelection();
  } catch (error) {
    console.error("下载操作失败:", error);
    $q.notify({
      type: "negative",
      message: "下载操作失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  }
};

const handleGetLink = async () => {
  const target =
    contextMenuData.value ||
    (selectedItems.value.length === 1 ? selectedItems.value[0] : null);

  if (!target || target.file_type === "directory") {
    $q.notify({
      type: "warning",
      message: "请选择一个文件",
      position: "top",
    });
    return;
  }

  try {
    // 显示加载通知
    const loadingNotify = $q.notify({
      type: "info",
      message: "正在获取下载链接...",
      position: "top",
      timeout: 0,
    });

    // 导入API
    const { getDownloadInfo } = await import("src/js/cloudApi");

    // 获取下载信息
    const downloadInfo = await getDownloadInfo(target.full_path);

    // 关闭加载通知
    loadingNotify();

    // 复制链接到剪贴板
    await navigator.clipboard.writeText(downloadInfo.download_url);

    // 显示成功通知
    $q.notify({
      type: "positive",
      message: `已复制 ${target.filename} 的临时直链到剪贴板`,
      position: "top",
      timeout: 3000,
    });

    // 清除选择
    clearSelection();
  } catch (error) {
    console.error("获取临时直链失败:", error);
    $q.notify({
      type: "negative",
      message: "获取临时直链失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  }
};

const handleImageHost = async () => {
  const target =
    contextMenuData.value ||
    (selectedItems.value.length === 1 ? selectedItems.value[0] : null);

  if (!target || target.file_type !== "directory") {
    $q.notify({
      type: "warning",
      message: "请选择一个文件夹",
      position: "top",
    });
    return;
  }

  try {
    // 显示加载状态
    const loadingNotify = $q.notify({
      type: "info",
      message: "正在获取图床配置...",
      position: "top",
      timeout: 0,
    });

    // 导入API
    const { getImageHostConfig } = await import("src/js/cloudApi");

    // 获取图床配置
    const config = await getImageHostConfig(target.full_path);

    // 关闭加载通知
    loadingNotify();

    // 显示图床设置对话框
    showImageHostDialog(target, config);
  } catch (error) {
    console.error("获取图床配置失败:", error);
    $q.notify({
      type: "negative",
      message: "获取图床配置失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  }
};

// 图床设置对话框相关状态
const showImageHostDialogVisible = ref(false);
const imageHostConfig = ref(null);
const imageHostTarget = ref(null);

const showImageHostDialog = (target, config) => {
  imageHostTarget.value = target;
  imageHostConfig.value = config;
  showImageHostDialogVisible.value = true;
};

// 启用图床功能
const enableImageHost = async () => {
  if (!imageHostTarget.value) return;

  try {
    // 导入API
    const { enableImageHost: enableImageHostApi } = await import(
      "src/js/cloudApi"
    );

    // 启用图床功能
    const newConfig = await enableImageHostApi(imageHostTarget.value.full_path);

    // 更新配置
    imageHostConfig.value = newConfig;
  } catch (error) {
    console.error("启用图床功能失败:", error);
  }
};

// 取消图床功能
const disableImageHost = async () => {
  if (!imageHostTarget.value) return;

  // 确认对话框
  $q.dialog({
    title: "确认取消",
    message: "确定要取消图床功能吗？这将删除所有图床配置。",
    cancel: true,
    persistent: true,
    ok: {
      label: "取消图床功能",
      color: "negative",
    },
  }).onOk(async () => {
    try {
      // 导入API
      const { disableImageHost: disableImageHostApi } = await import(
        "src/js/cloudApi"
      );

      // 取消图床功能
      await disableImageHostApi(imageHostTarget.value.full_path);

      // 更新配置
      imageHostConfig.value = { enabled: false };
    } catch (error) {
      console.error("取消图床功能失败:", error);
    }
  });
};

// 刷新Token
const refreshToken = async () => {
  if (!imageHostTarget.value) return;

  try {
    // 导入API
    const { refreshImageHostToken: refreshImageHostTokenApi } = await import(
      "src/js/cloudApi"
    );

    // 刷新Token
    const newConfig = await refreshImageHostTokenApi(
      imageHostTarget.value.full_path
    );

    // 更新配置
    imageHostConfig.value = newConfig;
  } catch (error) {
    console.error("刷新Token失败:", error);
  }
};

// 复制到剪贴板
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    $q.notify({
      type: "positive",
      message: "已复制到剪贴板",
      position: "top",
      timeout: 2000,
    });
  } catch (error) {
    console.error("复制失败:", error);
    $q.notify({
      type: "negative",
      message: "复制失败",
      position: "top",
      timeout: 2000,
    });
  }
};

// 显示图床使用帮助
const showImageHostHelp = () => {
  $q.dialog({
    title: "图床使用帮助",
    message: `
      <div style="text-align: left; line-height: 1.6;">
        <h4>Typora 配置示例：</h4>
        <p><strong>1. 打开 Typora 设置</strong></p>
        <p>文件 → 偏好设置 → 图像</p>

        <p><strong>2. 配置图床服务</strong></p>
        <p>选择"上传服务" → "自定义命令"</p>

        <p><strong>3. 配置上传命令</strong></p>
        <p>命令：<code>curl</code></p>
        <p>参数：<code>-X POST -F "image={image_path}" "${
          window.location.origin
        }/cloudImage?path=${
      imageHostTarget.value?.full_path || ""
    }" -H "ApiKey: ${btoa(
      localStorage.getItem("token") + "$$" + localStorage.getItem("email")
    )}"</code></p>

        <p><strong>4. 配置返回格式</strong></p>
        <p>返回格式：<code>JSON</code></p>
        <p>URL 路径：<code>url</code></p>

        <h4>其他编辑器配置：</h4>
        <p><strong>PicGo 配置：</strong></p>
        <p>类型：自定义</p>
        <p>URL：<code>${window.location.origin}/cloudImage?path=${
      imageHostTarget.value?.full_path || ""
    }</code></p>
        <p>POST 参数名：<code>image</code></p>
        <p>JSON 路径：<code>url</code></p>
        <p>请求头：<code>ApiKey: ${btoa(
          localStorage.getItem("token") + "$$" + localStorage.getItem("email")
        )}</code></p>

        <h4>API 说明：</h4>
        <p>• 支持格式：JPG, PNG, GIF, WebP</p>
        <p>• 最大文件大小：10MB</p>
        <p>• 返回格式：<code>{"url": "图片访问地址"}</code></p>
        <p>• 认证方式：ApiKey 请求头</p>
      </div>
    `,
    html: true,
    persistent: true,
    style: "max-width: 600px;",
    ok: {
      label: "关闭",
      color: "primary",
    },
  });
};

const handleOfflineDownload = () => {
  // 使用emit通知父组件处理离线下载
  emit("offline-download");
};

const openFolder = (folder) => {
  console.log("打开文件夹:", folder);

  // 从full_path中提取相对路径
  const newPath = getItemPath(folder.full_path);
  console.log("导航到路径:", newPath);

  // 更新当前路径
  currentPath.value = newPath;

  // 通知父组件路径更新
  emit("update-current-path", newPath);

  // 更新当前目录的项目
  updateCurrentDirectoryItems();

  // 清除选择
  clearSelection();
};

const openFile = async (file) => {
  console.log("打开文件:", file);

  try {
    // 显示加载通知
    const loadingNotify = $q.notify({
      type: "info",
      message: "正在准备文件内容...",
      position: "top",
      timeout: 0,
    });

    // 导入API
    const { getDownloadInfo } = await import("src/js/cloudApi");

    // 获取下载信息
    const downloadInfo = await getDownloadInfo(file.full_path);

    // 关闭加载通知
    loadingNotify();

    // 在新窗口打开下载链接
    window.open(downloadInfo.download_url, "_blank");

    // 显示成功通知
    $q.notify({
      type: "positive",
      message: `已在浏览器中打开 ${file.filename}`,
      position: "top",
      timeout: 3000,
    });
  } catch (error) {
    console.error("打开文件失败:", error);
    $q.notify({
      type: "negative",
      message: "打开文件失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  }
};

const navigateToBreadcrumb = (index) => {
  const breadcrumb = breadcrumbs.value[index];
  if (breadcrumb && breadcrumb.path !== currentPath.value) {
    console.log("面包屑导航到:", breadcrumb.path);

    // 更新当前路径
    currentPath.value = breadcrumb.path;

    // 通知父组件路径更新
    emit("update-current-path", breadcrumb.path);

    // 更新当前目录的项目
    updateCurrentDirectoryItems();

    // 清除选择
    clearSelection();
  }
};

// 刷新目录功能
const refreshDirectory = async () => {
  // 防止重复点击
  if (refreshing.value) {
    return;
  }

  try {
    refreshing.value = true;
    console.log("开始刷新目录，当前路径:", currentPath.value);

    // 重新获取根目录数据
    const { browseDirectory } = await import("src/js/cloudApi");
    const newData = await browseDirectory("/");

    if (newData && newData.items) {
      allItems.value = newData.items;
      console.log("刷新数据成功:", newData.items);

      // 验证当前路径是否仍然存在
      const validateCurrentPath = () => {
        if (currentPath.value === "/") {
          return true; // 根路径总是存在的
        }

        // 检查当前路径是否在数据中存在
        // 需要递归检查所有嵌套的目录结构
        const checkPathExists = (items, targetPath) => {
          for (const item of items) {
            if (item.file_type === "directory") {
              const itemPath = getItemPath(item.full_path);
              if (itemPath === targetPath) {
                return true;
              }
              // 如果这个目录有子项目，递归检查
              if (item.items && item.items.length > 0) {
                if (checkPathExists(item.items, targetPath)) {
                  return true;
                }
              }
            }
          }
          return false;
        };

        return checkPathExists(allItems.value, currentPath.value);
      };

      // 如果当前路径不存在，逐级返回上级目录
      let attempts = 0;
      const maxAttempts = 10; // 防止无限循环

      while (!validateCurrentPath() && attempts < maxAttempts) {
        console.log(`当前路径 ${currentPath.value} 不存在，返回上级目录`);

        // 返回上级目录
        const pathParts = currentPath.value.split("/").filter((p) => p);
        if (pathParts.length > 0) {
          pathParts.pop(); // 移除最后一级
          currentPath.value = "/" + pathParts.join("/");
        } else {
          // 如果已经是根目录，直接设置为根目录
          currentPath.value = "/";
          break;
        }

        attempts++;
      }

      if (attempts >= maxAttempts) {
        console.warn("达到最大尝试次数，重置到根目录");
        currentPath.value = "/";
      }

      // 更新当前目录的项目
      updateCurrentDirectoryItems();

      // 清除选择
      clearSelection();

      $q.notify({
        type: "positive",
        message: "刷新成功",
        position: "top",
        timeout: 2000,
      });
    }
  } catch (error) {
    console.error("刷新目录失败:", error);
    $q.notify({
      type: "negative",
      message: "刷新失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  } finally {
    refreshing.value = false;
  }
};

const setViewMode = (mode) => {
  viewMode.value = mode;
  $q.notify({
    type: "info",
    message: `切换到${mode === "grid" ? "网格" : "列表"}视图`,
    position: "top",
  });
};

const showMoreOptions = () => {
  $q.notify({
    type: "info",
    message: "更多选项功能开发中...",
    position: "top",
  });
};

const goToProfile = () => {
  window.open("https://login.zhuchundashuaige.com/", "_blank");
};

const getFileIcon = (file) => {
  const filename = file.filename.toLowerCase();
  const ext = filename.substring(filename.lastIndexOf("."));

  // 图片文件
  if (
    [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg"].includes(ext)
  ) {
    return "image";
  }
  // 视频文件
  if ([".mp4", ".avi", ".mov", ".wmv", ".flv", ".mkv"].includes(ext)) {
    return "videocam";
  }
  // 音频文件
  if ([".mp3", ".wav", ".flac", ".aac", ".ogg"].includes(ext)) {
    return "music_note";
  }
  // 文档文件
  if (
    [".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"].includes(ext)
  ) {
    return "description";
  }
  // 代码文件
  if (
    [
      ".js",
      ".ts",
      ".py",
      ".java",
      ".cpp",
      ".c",
      ".html",
      ".css",
      ".json",
      ".xml",
    ].includes(ext)
  ) {
    return "code";
  }
  // 压缩文件
  if ([".zip", ".rar", ".7z", ".tar", ".gz"].includes(ext)) {
    return "archive";
  }
  // 默认文件图标
  return "insert_drive_file";
};

const getFileColor = (file) => {
  const filename = file.filename.toLowerCase();
  const ext = filename.substring(filename.lastIndexOf("."));

  // 图片文件
  if (
    [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".svg"].includes(ext)
  ) {
    return "green";
  }
  // 视频文件
  if ([".mp4", ".avi", ".mov", ".wmv", ".flv", ".mkv"].includes(ext)) {
    return "red";
  }
  // 音频文件
  if ([".mp3", ".wav", ".flac", ".aac", ".ogg"].includes(ext)) {
    return "orange";
  }
  // 文档文件
  if (
    [".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx"].includes(ext)
  ) {
    return "blue";
  }
  // 代码文件
  if (
    [
      ".js",
      ".ts",
      ".py",
      ".java",
      ".cpp",
      ".c",
      ".html",
      ".css",
      ".json",
      ".xml",
    ].includes(ext)
  ) {
    return "purple";
  }
  // 压缩文件
  if ([".zip", ".rar", ".7z", ".tar", ".gz"].includes(ext)) {
    return "brown";
  }
  // 默认颜色
  return "grey";
};

const getFileType = (file) => {
  const filename = file.filename.toLowerCase();
  const ext = filename.substring(filename.lastIndexOf("."));

  if (ext) {
    return ext.substring(1).toUpperCase();
  }

  // 如果没有扩展名，尝试从file_type字段获取
  if (file.file_type) {
    return file.file_type;
  }

  return "未知";
};

const formatTime = (timeString) => {
  if (!timeString) return "-";

  try {
    const date = new Date(timeString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    const seconds = String(date.getSeconds()).padStart(2, "0");

    return `${year}年${month}月${day}日 pm${hours}:${minutes}:${seconds} CST`;
  } catch (error) {
    console.error("时间格式化错误:", error);
    return "-";
  }
};

const formatFileSize = (size) => {
  if (!size || size === 0) return "-";

  const units = ["B", "KB", "MB", "GB", "TB"];
  let sizeInBytes = size;
  let unitIndex = 0;

  while (sizeInBytes >= 1024 && unitIndex < units.length - 1) {
    sizeInBytes /= 1024;
    unitIndex++;
  }

  return `${sizeInBytes.toFixed(1)} ${units[unitIndex]}`;
};

// 从full_path中提取相对路径
const getItemPath = (fullPath) => {
  if (!fullPath) return "/";
  const pathParts = fullPath.split("/");
  if (pathParts.length > 2) {
    return "/" + pathParts.slice(2, -1).join("/");
  }
  return "/";
};

// 从full_path中提取文件/目录名
const getItemName = (fullPath) => {
  if (!fullPath) return "";
  const pathParts = fullPath.split("/");
  return pathParts[pathParts.length - 1] || "";
};

// 从full_path中提取目录路径
const getItemDirectory = (fullPath) => {
  if (!fullPath) return "/";
  const pathParts = fullPath.split("/");
  if (pathParts.length > 2) {
    return "/" + pathParts.slice(2, -1).join("/");
  }
  return "/";
};

// 监听props变化
watch(
  () => props.directoryData,
  async (newData) => {
    if (newData) {
      console.log("接收到新的目录数据:", newData);

      // 开始处理数据时显示loading
      processingData.value = true;

      try {
        // 如果接收到数据，设置为所有项目
        if (Array.isArray(newData)) {
          allItems.value = newData;
          console.log("设置所有项目:", newData);

          // 更新当前目录的项目
          updateCurrentDirectoryItems();
        }
      } finally {
        // 处理完成后隐藏loading
        processingData.value = false;
      }
    }
  },
  { immediate: true }
);

// 生命周期
onMounted(() => {
  // 添加全局点击事件监听器，用于关闭上下文菜单
  document.addEventListener("click", handleGlobalClick);

  // 添加全局拖拽事件监听器
  document.addEventListener("dragenter", handleDragEnter);
  document.addEventListener("dragleave", handleDragLeave);
  document.addEventListener("dragover", handleDragOver);
  document.addEventListener("drop", handleDrop);

  // 添加键盘事件监听器
  document.addEventListener("keydown", handleKeyDown);

  // 监听任务队列事件
  taskQueue.on("taskCompleted", handleTaskCompleted);
  taskQueue.on("taskFailed", handleTaskFailed);

  // 启动任务队列
  taskQueue.start();
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener("click", handleGlobalClick);

  // 移除全局拖拽事件监听器
  document.removeEventListener("dragenter", handleDragEnter);
  document.removeEventListener("dragleave", handleDragLeave);
  document.removeEventListener("dragover", handleDragOver);
  document.removeEventListener("drop", handleDrop);

  // 移除键盘事件监听器
  document.removeEventListener("keydown", handleKeyDown);

  // 移除任务队列事件监听器
  taskQueue.off("taskCompleted", handleTaskCompleted);
  taskQueue.off("taskFailed", handleTaskFailed);

  // 清理防抖定时器
  if (refreshTimeout.value) {
    clearTimeout(refreshTimeout.value);
  }

  // 清理批量上传定时器
  if (batchUploadTimeout.value) {
    clearTimeout(batchUploadTimeout.value);
  }
});

// 全局点击事件处理
const handleGlobalClick = (event) => {
  // 如果点击的不是菜单内部元素，则关闭菜单
  if (showContextMenu.value && !event.target.closest(".context-menu")) {
    showContextMenu.value = false;
  }
};

// 键盘事件处理
const handleKeyDown = (event) => {
  // 如果当前焦点在输入框中，不处理快捷键
  if (event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA") {
    return;
  }

  switch (event.key) {
    case "Delete":
    case "Backspace":
      // 删除选中的项目
      if (selectedItems.value.length > 0) {
        event.preventDefault();
        handleDelete();
      }
      break;
    case "Escape":
      // 取消选择
      if (selectedItems.value.length > 0) {
        event.preventDefault();
        clearSelection();
      }
      break;
  }
};

// 拖拽上传相关方法
const handleDragEnter = (event) => {
  event.preventDefault();

  // 检查是否是文件拖拽
  if (event.dataTransfer && event.dataTransfer.types.includes("Files")) {
    dragCounter.value++;
    showDropZone.value = true;
  }
};

const handleDragLeave = (event) => {
  event.preventDefault();

  // 检查是否是文件拖拽
  if (event.dataTransfer && event.dataTransfer.types.includes("Files")) {
    dragCounter.value--;
    if (dragCounter.value === 0) {
      showDropZone.value = false;
    }
  }
};

const handleDragOver = (event) => {
  event.preventDefault();
};

const handleDrop = async (event) => {
  event.preventDefault();
  dragCounter.value = 0;
  showDropZone.value = false;

  const files = Array.from(event.dataTransfer.files);

  if (files.length === 0) {
    return;
  }

  // 使用与handleUpload相同的文件验证逻辑
  const maxFileSize = 100 * 1024 * 1024; // 100MB
  const validFiles = [];
  const invalidFiles = [];

  for (const file of files) {
    // 检查文件大小
    if (file.size > maxFileSize) {
      invalidFiles.push(`${file.name} (文件过大，超过100MB)`);
      continue;
    }

    // 检查文件名长度
    if (file.name.length > 255) {
      invalidFiles.push(`${file.name} (文件名过长，超过255字符)`);
      continue;
    }

    // 检查文件名是否包含非法字符
    const invalidChars = /[<>:"/\\|?*]/;
    if (invalidChars.test(file.name)) {
      invalidFiles.push(`${file.name} (文件名包含非法字符)`);
      continue;
    }

    validFiles.push(file);
  }

  // 显示无效文件警告
  if (invalidFiles.length > 0) {
    $q.notify({
      type: "warning",
      message: `以下文件无法上传：\n${invalidFiles.join("\n")}`,
      position: "top",
      timeout: 5000,
      html: true,
    });
  }

  // 如果没有有效文件，直接返回
  if (validFiles.length === 0) {
    return;
  }

  try {
    // 为每个有效文件创建上传任务
    for (let i = 0; i < validFiles.length; i++) {
      const file = validFiles[i];

      // 添加到任务队列
      taskQueue.addTask(TaskType.UPLOAD, {
        file: file,
        targetPath: currentPath.value,
      });
    }

    // 成功通知
    $q.notify({
      type: "positive",
      message: `已添加 ${validFiles.length} 个上传任务到队列`,
      position: "top",
      timeout: 3000,
    });
  } catch (error) {
    console.error("添加上传任务失败:", error);
    $q.notify({
      type: "negative",
      message: "添加上传任务失败: " + (error.message || "未知错误"),
      position: "top",
      timeout: 3000,
    });
  }
};

// 防抖刷新函数
const debouncedRefresh = () => {
  // 清除之前的定时器
  if (refreshTimeout.value) {
    clearTimeout(refreshTimeout.value);
  }

  // 设置新的定时器
  refreshTimeout.value = setTimeout(() => {
    if (pendingRefresh.value) {
      console.log("执行防抖刷新，已完成任务数:", completedTasks.value.length);
      refreshDirectory();
      pendingRefresh.value = false;
      completedTasks.value = [];
    }
  }, 1000); // 1000ms 防抖延迟
};

// 任务完成处理
const handleTaskCompleted = (task) => {
  console.log("任务完成:", task);

  // 添加到已完成任务列表
  completedTasks.value.push(task);

  // 根据任务类型显示不同的通知
  let message = task.result?.message || "任务完成";
  let shouldShowNotify = true;

  switch (task.type) {
    case TaskType.DELETE:
      message = "删除完成";
      break;
    case TaskType.RENAME:
      message = "重命名完成";
      break;
    case TaskType.UPLOAD:
      // 处理批量上传通知
      if (batchUploadCount.value > 1) {
        completedUploadCount.value++;

        // 如果所有文件都上传完成，显示汇总通知
        if (completedUploadCount.value === batchUploadCount.value) {
          message = `批量上传完成 (${batchUploadCount.value} 个文件)`;
          // 重置批量上传状态
          batchUploadCount.value = 0;
          completedUploadCount.value = 0;
        } else {
          // 批量上传中，不显示单个文件的通知
          shouldShowNotify = false;
        }
      } else {
        // 单个文件上传，显示详细信息
        const fileName = task.result?.fileName || task.data?.fileName || "文件";
        const fileSize = task.result?.fileSize || task.data?.fileSize;
        if (fileSize) {
          const sizeStr = formatFileSize(fileSize);
          message = `${fileName} (${sizeStr}) 上传完成`;
        } else {
          message = `${fileName} 上传完成`;
        }
      }
      break;
    case TaskType.OFFLINE_DOWNLOAD:
      // 离线下载任务显示更详细的信息
      const downloadFileName =
        task.result?.fileName || task.data?.fileName || "文件";
      const fileInfo = task.result?.fileInfo;
      if (fileInfo && fileInfo.size) {
        const sizeStr = formatFileSize(fileInfo.size);
        message = `${downloadFileName} (${sizeStr}) 离线下载任务已创建`;
      } else {
        message = `${downloadFileName} 离线下载任务已创建`;
      }
      break;
    case TaskType.CREATE_FOLDER:
      // 创建文件夹任务显示更详细的信息
      const folderName =
        task.result?.fileName || task.data?.folderName || "文件夹";
      message = `文件夹 ${folderName} 创建成功`;
      break;
  }

  // 只在需要时显示通知
  if (shouldShowNotify) {
    $q.notify({
      type: "positive",
      message: message,
      position: "bottom-left",
      timeout: 2000,
      actions: [{ label: "关闭", color: "white" }],
    });
  }

  // 对于会影响文件结构的操作，设置防抖刷新
  if (
    task.type === TaskType.DELETE ||
    task.type === TaskType.RENAME ||
    task.type === TaskType.UPLOAD ||
    task.type === TaskType.OFFLINE_DOWNLOAD ||
    task.type === TaskType.CREATE_FOLDER
  ) {
    pendingRefresh.value = true;
    debouncedRefresh();
  }
};

// 任务失败处理
const handleTaskFailed = (task) => {
  console.error("任务失败:", task);

  $q.notify({
    type: "negative",
    message: `任务失败: ${task.error?.message || "未知错误"}`,
    position: "top",
    timeout: 5000,
  });
};
</script>

<style scoped>
.item-list {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.item-header {
  display: grid;
  grid-template-columns: 40px 2fr 1fr 1.5fr 1fr;
  gap: 16px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e0e0e0;
  font-weight: 600;
  font-size: 14px;
  color: #666;
}

.item-row {
  display: grid;
  grid-template-columns: 40px 2fr 1fr 1.5fr 1fr;
  gap: 16px;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s ease;
}

.item-row:last-child {
  border-bottom: none;
}

.item-row:hover {
  background-color: #f5f5f5;
}

.item-row.item-selected {
  background-color: #e3f2fd;
}

.item-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-name-cell {
  display: flex;
  align-items: center;
  overflow: hidden;
}

.item-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.item-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 14px;
  color: #333;
}

.item-type,
.item-time,
.item-size {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-name,
.header-type,
.header-time,
.header-size,
.header-checkbox {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 上下文菜单样式 */
.context-menu {
  position: fixed;
  z-index: 9999;
  user-select: none;
}

/* 拖拽上传区域样式 */
.drop-zone {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.drop-zone-content {
  text-align: center;
  padding: 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  max-width: 400px;
  width: 90%;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .item-header {
    grid-template-columns: 40px 1fr 80px 100px;
    gap: 8px;
    padding: 8px 12px;
    font-size: 12px;
  }

  .item-row {
    grid-template-columns: 40px 1fr 80px 100px;
    gap: 8px;
    padding: 8px 12px;
  }

  .item-type {
    display: none;
  }

  .header-type {
    display: none;
  }
}
</style>
